<?php
/**
 * Created by PhpStorm.
 * User: Digvijay
 * Date: 8/30/14
 * Time: 1:49 PM
 */

class Shop extends MY_Home {
    public function isUserLoggedIn() {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $result = null;
        if ($this->isClientLoggedIn() == null) {
            $result = array("loggedIn" => false);
        } else {
            $result = array("loggedIn" => true);
        }
        header('Content-Type: application/json');
        echo json_encode($result, JSON_PRETTY_PRINT);
    }

    public function registerandplaceorder(){
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try{
            $businessName = trim($this->input->post("business-name"));
            $firstName = trim($this->input->post("first-name"));
            $lastName = trim($this->input->post("last-name"));
            $phone = trim($this->input->post("phone"));
            $email = trim($this->input->post("email"));

            $agent = $this->findAgencyByEmail($email);
            if(count($agent) == 0){
                $agent = new Agency();
                $agent->setEmail($email);
                $agent->setFirstName($firstName);
                $agent->setLastName($lastName);
                $agent->setBusinessName($businessName);
                $agent->setPhone($phone);
                $agent->setClientType(Agency::CLIENT_ANONYMOUS);
                $agent->setDateCreate(new DateTime());
                $this->save($agent);

            }else if($agent[0]->getClientType() == Agency::CLIENT_AGENT){
                throw new RuntimeException("This email is Registered with us, please login and completed order.");
            }
            if($this->session->userdata('logged_in')){
                $sessionData = $this->session->userdata('logged_in');
                if($sessionData['type'] == 'ANONYMOUS'){
                    $agent = $this->findAgencyByEmail($email)[0];
                    $sessionData['agentId'] = $agent->getId();
                    $sessionData['registered'] = true;
                    $this->session->set_userdata('logged_in', $sessionData);
                    $response = $this->processOrder();

                    $this->session->sess_destroy();
                    $this->session->unset_userdata('logged_in');
                }else{
                    throw new RuntimeException("Invalid Request");
                }
            }
        }catch (Exception $e){
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    public function addToCart($productId = null, $locationId = null, $quantity = null) {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            if ($productId != null && $locationId != null && $quantity != null) {
                $product = $this->findById("Product", $productId);
                $headerImg = null;
                foreach ($product->getImages() as $img) {
                    if ($img->getIsCover()) {
                        $headerImg = $img->getName();
                        break;
                    }
                }
                foreach ($product->getStock() as $stock) {
                    if ($stock->getLocation()->getId() == $locationId && $stock->getActualStock() >= $quantity) {
                        //Check if user is registered User.
                        $user = $this->isClientLoggedIn();
                        $discount = $product->getDiscount();
                        if ($user == null) {
                            //Probably Anonymous user, Let's create session for him.
                            $sessionData = array("agentId" => '', "type" => "ANONYMOUS", "registered" => false);
                            $this->session->set_userdata('logged_in', $sessionData);
                        } else {
                            $discount = $this->getDiscountForLoggedInUser();
                        }
                        $price = ($product->getPrice() / 100);
                        $data = array(
                            'id' => $productId,
                            'qty' => $quantity,
                            'price' => $price,
                            'name' => $product->getName(),
                            'options' => array('location' => $locationId, 'discount' => $discount, 'img' => $headerImg)
                        );
                        $this->cart->insert($data);
                    }
                }
            }
            $cartItems = array();
            foreach ($this->cart->contents() as $item) {
                $cartitem = new Cartitem();
                $cartitem->setCartId($item["rowid"]);
                $cartitem->setId($item["id"]);
                $cartitem->setName($item["name"]);
                $cartitem->setQuantity($item["qty"]);
                $cartitem->setPrice($item["price"]);
                $cartitem->setSubtotal($item["subtotal"]);
                $cartitem->setLocationId($item["options"]["location"]);
                $cartitem->setLocation($this->findById("Branch", $item["options"]["location"])->getName());
                $cartitem->setImg($item["options"]["img"]);
                $cartitem->setDiscount($item["options"]["discount"]);

                $discount = $item["options"]["discount"];
                $subTotal = $item["subtotal"];
                if ($discount > 0) {
                    $subTotal = $subTotal - ($subTotal * ($discount / 100));
                }
                $cartitem->setDiscountTotal($subTotal);
                array_push($cartItems, $cartitem);
            }
            $response->setData($cartItems);
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    public function removeFromCart($id = null) {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = new Response();
        try {
            if ($id != null) {
                $data = array(
                    'rowid' => $id,
                    'qty' => 0
                );
                $this->cart->update($data);

                $cartItems = array();
                foreach ($this->cart->contents() as $item) {
                    $cartitem = new Cartitem();
                    $cartitem->setCartId($item["rowid"]);
                    $cartitem->setId($item["id"]);
                    $cartitem->setName($item["name"]);
                    $cartitem->setQuantity($item["qty"]);
                    $cartitem->setPrice($item["price"]);
                    $cartitem->setSubtotal($item["subtotal"]);
                    $cartitem->setLocationId($item["options"]["location"]);
                    $cartitem->setLocation($this->findById("Branch", $item["options"]["location"])->getName());
                    $cartitem->setImg($item["options"]["img"]);
                    $cartitem->setDiscount($item["options"]["discount"]);

                    $discount = $item["options"]["discount"];
                    $subTotal = $item["subtotal"];
                    if ($discount > 0) {
                        $subTotal = $subTotal - ($subTotal * ($discount / 100));
                    }
                    $cartitem->setDiscountTotal($subTotal);
                    array_push($cartItems, $cartitem);
                }
                $response->setData($cartItems);
            } else {
                throw new RuntimeException("Invalid Request");
            }
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    public function placeOrder() {
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        $response = $this->processOrder();
        header('Content-Type: application/json');
        echo json_encode($response, JSON_PRETTY_PRINT);
    }

    private function processOrder(){
        $response = new Response();
        try {

            $locationsOrders = array();
            foreach ($this->cart->contents() as $item) {
                $locationId = $item["options"]["location"];

                if(!array_key_exists($locationId, $locationsOrders)){
                    $locationsItems = array();
                    $locationsOrders[$locationId] = $locationsItems;
                }

                $locationItems = $locationsOrders[$locationId];

                $productId = $item["id"];
                $qty = $item["qty"];
                $price = $item["price"];
                $discount = $item["options"]["discount"];
                $branch = $this->findById("Branch", $locationId);

                $product = $this->findById("Product", $productId);
                if ($product->getProductActualStockByLocation($branch) >= $qty) {
                    $orderItem = new OrderItem();
                    $orderItem->setPrice($price);
                    $orderItem->setProduct($product);
                    $orderItem->setBranch($branch);
                    $orderItem->setQuantity($qty);
                    $orderItem->setDiscount($discount);

                    array_push($locationItems, $orderItem);

                    $locationsOrders[$locationId] = $locationItems;

                    //Updating Inventory.
                    $product->updateProductStockByBranch($branch, $qty);
                    $this->save($product);
                }
            }

            $loggedInUser = $this->session->userdata('logged_in');
            $notification = $this->findById("Notification", 1);
            $agency = null;
            $agentEmail = null;
            $agencyDiscount = null;

            if ($loggedInUser["agentId"] != "") {
                $agency = $this->findById("Agency", $loggedInUser["agentId"]);
                $agentEmail = $agency->getEmail();
                $agencyDiscount = $agency->getDiscount();
                $emailData["client"] = $agency;
            }else{
                throw new RuntimeException("Invalid Request");
            }

            $orderNumbers = array();
            $branchEmails = array();
            foreach($locationsOrders as $key => $items){
                $order = new Order();
                $orderTotal = 0;

                $branchEmail = null;
                foreach($items as $item){
                    $branchEmail = $item->getBranch()->getEmail();
                    $discount = $item->getDiscount();
                    if($agencyDiscount != null){
                        $discount = $agencyDiscount;
                    }
                    $totalItemPrice = $item->getQuantity() * $item->getPrice();
                    $subTotal = $totalItemPrice;
                    if ($discount > 0) {
                        $subTotal = $totalItemPrice - ($totalItemPrice * ($discount / 100));
                    }
                    $orderTotal += $subTotal;
                    $order->addItem($item);
                }
                $order->setPrice($orderTotal);
                $order->setOrderDate(new DateTime());
                $order->setStatus(Order::ORDER_PENDING);
                $order->setAgency($agency);
                $this->save($order);

                $emailData = array("client"=>$agency, "order"=>$order);
                try{
                    $this->sendOrderDetailsMail($agentEmail,"Order Placed", $emailData);
                    $this->sendOrderDetailsMail($branchEmail,"Order Place", $emailData);
                    $this->sendOrderDetailsMail($notification->getOrderPlaceEmail(),"Order Place", $emailData);
                }catch(Exception $e1){
                }
                array_push($orderNumbers,$order->getId());
            }
            $orderNumberString = "";
            foreach($orderNumbers as $orderNos){
                $orderNumberString .= $orderNos . ", ";
            }
            $data = array("orderId" => $orderNumberString, "email" => $agentEmail, "message" => $notification->getOrderMessage());
            $response->setData($data);
            //Destroy Cart, Order is placed and Confirmed.
            $this->cart->destroy();
        } catch (Exception $e) {
            $response->setError(true);
            $response->setErrorMessage($e->getMessage());
        }
        return $response;
    }

    public function subscribe(){
        if (!$this->input->is_ajax_request()) {
            show_404();
            return;
        }
        try{
            $email = trim($this->input->post("subscribe_email"));
            if($email != null && $email != ""){
                $subscribe = new Subscribe();
                $subscribe->setEmail($email);
                $this->save($subscribe);
            }
        }catch(Exception $e){
        }
    }
} 